import userFriendGroupDao from "../dao/userfriendgroupDB.js";
import groupBaseInfoDao from "../dao/groupbaseinfoDB.js";
import {getNow, getUniSessionID, httpResult} from "../utils/utils.js";
import userAddMsgDao from "../dao/useraddmsg.js";
import userBaseDao from "../dao/userbaseDB.js";
import sequelize from "../models/initSequelize.js";
//发起 好友/群聊 申请
export const startRequest = async (req, res, next) => {
  let {account, requestAccount, type, remark, sendMessage} = req.query;
  if (!account || !requestAccount) {
    throw new Error("请输入账号和添加账号");
    return;
  }
  let isExisted = await userBaseDao.isExisted(account);
  if (!isExisted) {
    throw new Error('请输入正确的用户账号！');
    return;
  }
  type = Number(type) || 0;
  if (type) {
    let groupIsExisted = await groupBaseInfoDao.isExistedByAccount(requestAccount);
    if (!groupIsExisted) {
      throw new Error("请输入正确的群聊账号!");
      return;
    }
    let userIsInGroup = await userFriendGroupDao.isExisted(account, "", groupIsExisted._session_id, type);
    if (userIsInGroup) {
      throw new Error("您已在该群，请不要重复添加!");
      return;
    }
    let userAddMsgIsExisted = await userAddMsgDao.isExisted(account, groupIsExisted._leader, groupIsExisted._session_id, type);
    if (userAddMsgIsExisted) {
      //修改请求信息
      await userAddMsgDao.updateUserAddMsg(account, groupIsExisted._leader, groupIsExisted._session_id, sendMessage, getNow(), remark, type, 0);
    } else {
      //增加请求信息
      await userAddMsgDao.addUserAddMsg(account, groupIsExisted._leader, groupIsExisted._session_id, sendMessage, getNow(), remark, type, 0);
    }
    res.json(httpResult.success("发起群聊申请成功！"));
    return;
  }
  let isFriendExisted = await userBaseDao.isExisted(requestAccount);
  if (!isFriendExisted) {
    throw new Error('请输入正确的好友账号！');
    return;
  }
  let userIsFriend = await userFriendGroupDao.isExisted(account, requestAccount, "", type);
  console.log(userIsFriend);
  if (userIsFriend) {
    throw new Error("您已经是该用户好友，请不要重复添加!");
    return;
  }
  let userAddMsgIsExisted = await userAddMsgDao.isExisted(account, requestAccount, "", type);
  if (userAddMsgIsExisted) {
    //修改请求信息
    await userAddMsgDao.updateUserAddMsg(account, requestAccount, "", sendMessage, getNow(), remark, type, 0);
  } else {
    //增加请求信息
    await userAddMsgDao.addUserAddMsg(account, requestAccount, "", sendMessage, getNow(), remark, type, 0);
  }
  res.json(httpResult.success("发起好友申请成功！"));
  return;
};
//同意 好友/群聊 申请
export const agreeRequest = async (req, res, next) => {
  let {agreer, senderAccount, receiverAccount, type, sessionID} = req.query;
  if (!agreer || !senderAccount) {
    throw new Error("请输入账号和审批信息!");
    return;
  }
  type = Number(type) || 0;
  if (type) {
    if (!sessionID) {
      throw new Error("请输入账号和审批信息!");
      return;
    }
    let requestInfo = await userAddMsgDao.isExisted(senderAccount, "", sessionID, type);
    if (!requestInfo) {
      throw new Error("申请信息错误，请联系管理员!");
      return;
    }
    let groupLeader = await groupBaseInfoDao.isExistedBySessionID(sessionID);
    if (!groupLeader) {
      throw new Error("群组已解散!");
      return;
    }
    let isExistedMember = await userFriendGroupDao.isExisted(senderAccount, "", sessionID, 1);
    if (isExistedMember) {
      throw new Error("该用户已经在群里请勿重复添加!");
      return;
    }
    if (agreer !== groupLeader._leader) {
      throw new Error("您没有审批权限!");
      return;
    }
    const t = await sequelize.transaction();
    try {
      let updateResult = await userAddMsgDao.updateUserAddMsg(senderAccount, groupLeader._leader, sessionID, requestInfo._send_message, requestInfo._send_timestamp, requestInfo._sender_remark, type, 1, t);
      if (updateResult[0] === 0) {
        await t.rollback();
        throw new Error("申请信息错误，请联系管理员!!");
        return;
      }
      await userFriendGroupDao.addUserFriendGroup(senderAccount, groupLeader._group_account, sessionID, type, requestInfo._sender_remark, t);
      await t.commit();
    } catch (e) {
      await t.rollback();
      throw new Error("审批失败请联系管理员！");
      return;
    }
    res.json(httpResult.success('审批成功！'));
    return;
  }
  if (!receiverAccount) {
    throw new Error("请输入账号和审批信息!");
    return;
  }
  if (agreer !== receiverAccount) {
    throw new Error("您没有审批权限!");
    return;
  }
  let requestInfo = await userAddMsgDao.isExisted(senderAccount, receiverAccount, "", type);
  console.log(requestInfo);
  if (!requestInfo) {
    throw new Error("申请信息错误，请联系管理员!!!");
    return;
  }
  let isExistedFriends = await userFriendGroupDao.isExisted(senderAccount, receiverAccount, "", 0);
  if (isExistedFriends) {
    throw new Error("您已经是好友请勿重复添加!");
    return;
  }
  const t = await sequelize.transaction();
  try {
    let updateResult = await userAddMsgDao.updateUserAddMsg(senderAccount, receiverAccount, "", requestInfo._send_message, requestInfo._send_timestamp, requestInfo._sender_remark, type, 1, t);
    if (updateResult[0] === 0) {
      await t.rollback();
      throw new Error("申请信息错误，请联系管理员!");
      return;
    }
    let session_id = await getUniSessionID();
    await userFriendGroupDao.addUserFriendGroup(senderAccount, receiverAccount, session_id, type, requestInfo._sender_remark, t);
    await userFriendGroupDao.addUserFriendGroup(receiverAccount, senderAccount, session_id, type, "", t);
    await t.commit();
  } catch (e) {
    console.log(e);
    await t.rollback();
    throw new Error("审批失败请联系管理员！");
    return;
  }
  res.json(httpResult.success('审批成功！'));
  return;
};
//拒绝 好友/群聊 申请
export const refuseRequest = async (req, res, next) => {
  let {agreer, senderAccount, receiverAccount, type, sessionID} = req.query;
  if (!agreer || !senderAccount) {
    throw new Error("请输入账号和审批信息!");
    return;
  }
  type = Number(type) || 0;
  if (type) {
    if (!sessionID) {
      throw new Error("请输入账号和审批信息!");
      return;
    }
    let requestInfo = await userAddMsgDao.isExisted(senderAccount, "", sessionID, type);
    if (!requestInfo) {
      throw new Error("申请信息错误，请联系管理员!");
      return;
    }
    let groupLeader = await groupBaseInfoDao.isExistedBySessionID(sessionID);
    if (!groupLeader) {
      throw new Error("群组已解散!");
      return;
    }
    if (agreer !== groupLeader._leader) {
      throw new Error("您没有审批权限!");
      return;
    }
    const t = await sequelize.transaction();
    try {
      let updateResult = await userAddMsgDao.updateUserAddMsg(senderAccount, groupLeader._leader, sessionID, requestInfo._send_message, requestInfo._send_timestamp, requestInfo._sender_remark, type, 2, t);
      if (updateResult[0] === 0) {
        await t.rollback();
        throw new Error("申请信息错误，请联系管理员!");
        return;
      }
      await t.commit();
    } catch (e) {
      await t.rollback();
      throw new Error("审批失败请联系管理员！");
      return;
    }
    res.json(httpResult.success('审批成功！'));
    return;
  }
  if (!receiverAccount) {
    throw new Error("请输入账号和审批信息!");
    return;
  }
  if (agreer !== receiverAccount) {
    throw new Error("您没有审批权限!");
    return;
  }
  let requestInfo = await userAddMsgDao.isExisted(senderAccount, receiverAccount, "", type);
  if (!requestInfo) {
    throw new Error("申请信息错误，请联系管理员!");
    return;
  }
  const t = await sequelize.transaction();
  try {
    let updateResult = await userAddMsgDao.updateUserAddMsg(senderAccount, receiverAccount, "", requestInfo._send_message, requestInfo._send_timestamp, requestInfo._sender_remark, type, 2, t);
    if (updateResult[0] === 0) {
      await t.rollback();
      throw new Error("申请信息错误，请联系管理员!");
      return;
    }
    await t.commit();
  } catch (e) {
    await t.rollback();
    throw new Error("审批失败请联系管理员！");
    return;
  }
  res.json(httpResult.success('审批成功！'));
  return;
};
//获取所有申请
export const getRequestList = async (req, res, next) => {
  let account = req.headers['authorization'].split(" ")[2];
  let requestList = await userAddMsgDao.getUserAddMsg(account, 0);
  res.json(httpResult.success({msg: "获取成功", requestList}));
};
